/**
 * 部门管理模块
 */
const router = require('koa-router')();
const md5 = require('md5');
const deptDB = require('../models/deptSchema');
const jwt = require('../utils/jwt');
const util = require('../utils/util');

router.prefix('/dept');

// 递归拼接树形列表
function getTreeDept(rootList, id, list) {
  for (let i = 0; i < rootList.length; i++) {
    let item = rootList[i];
    if (String(item.parentId.slice().pop()) == String(id)) {
      list.push(item._doc);
    }
  }
  list.map((item) => {
    item.children = [];
    getTreeDept(rootList, item._id, item.children);
    if (item.children.length === 0) {
      delete item.children;
    }
  });
  return list;
}

// 查询部门列表
router.get('/list', async (ctx) => {
  let { deptName } = ctx.request.query;
  let params = {};
  if (deptName) {
    // 部门名称模糊查询
    let rootList = await deptDB.find({ deptName: new RegExp(deptName) });
    ctx.body = util.success(rootList);
  } else {
    let rootList = await deptDB.find(params);
    // 一级菜单的  id 是null
    ctx.body = util.success(getTreeDept(rootList, null, []));
  }
});

router.post('/add', async (ctx) => {
  let { _id, ...params } = ctx.request.body;
  try {
    await deptDB.create(params);
    ctx.body = util.success({}, '创建成功');
  } catch (error) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

router.post('/edit', async (ctx) => {
  let { _id, ...params } = ctx.request.body;
  try {
    params.updateTime = Date.now();
    await deptDB.findByIdAndUpdate(_id, params);
    ctx.body = util.success({}, '编辑成功');
  } catch (error) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

router.post('/delete', async (ctx) => {
  let { _id } = ctx.request.body;
  try {
    await deptDB.findByIdAndRemove(_id);
    await deptDB.deleteMany({ parentId: { $all: [_id] } });
    ctx.body = util.success({}, '删除成功');
  } catch (error) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

module.exports = router;
